<template>
  <div class='container'>
    <el-dialog title="新增学科" :visible="addDialogVisible" width="20%" @close="resetSub">
      <!-- 主体区域 -->
      <el-row>
        <el-col>
          <el-form :model="addSubjectDate" :rules="rules" ref="addSubjectsFrom" label-width="80px" class="demo-ruleForm">
            <el-form-item label="学科名称" prop="subjectName">
              <el-input v-model="addSubjectDate.subjectName" placeholder="请输入学科名称"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <span class="subspan">是否显示</span>
        <el-switch v-model="SubSwitchValue" active-color="#13ce66" inactive-color="#ff4949"> </el-switch>
      </el-row>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubject">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
// 引入添加学科列表的方法
import { add as addSubjectList } from '@/api/hmmm/subjects'
export default {
  props: {
    addDialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      // 学科添加的数据
      addSubjectDate: {
        subjectName: ''
      },
      // 控制switch的状态
      SubSwitchValue: true,
      // 添加数据表单的规则
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      }

    }
  },
  computed: {
    isFrontDisplay () {
      if (this.SubSwitchValue) {
        return 1
      } else {
        return 0
      }
    }
  },
  methods: {
    // 关闭弹框
    resetSub () {
      //  重置表单和光比弹框是一起的
      this.addSubjectDate = {
        subjectName: ''
      }
      this.$emit('update:addDialogVisible', false)
    },
    // 确定按钮、
    addSubject () {
      // 手动校验数据
      this.$refs.addSubjectsFrom.validate()
        .then(() => {
          console.log('校验成功')
          return addSubjectList({
            subjectName: this.addSubjectDate.subjectName,
            isFrontDisplay: this.isFrontDisplay
          })
        })
        .then(() => {
          this.$message.success('添加成功')
          // 关闭弹框
          this.$emit('update:addDialogVisible', false)
          // 告诉父组件我做完了，重新获取数据
          this.$emit('done')
        })
        .catch(() => {
          console.log('校验失败')
        })
      // console.log(this.addSubjectDate.isFrontDisplay)
      console.log(this.addSubjectDate)
    }
  }
}
</script>

<style scoped >
.container .subspan {
  font-size: 14px;
    font-weight: 700;
    margin-right: 10px;
    margin-left: 10px;
}
.container el-switch {
  margin-left: 10px;
}</style>
